import cv2

def get_frames(path, n, imgdir):
    cap=cv2.VideoCapture(path)
    videoname=path.split('/')[-1].split('.')[0]
    # print(videoname)
    fps=cap.get(cv2.CAP_PROP_FPS)
    print('fps:',fps)
    fps/=n
    print(fps)

    index=0 #记录采样的帧号
    need=fps-int(fps)<0.5 #记录是否需要不等间隔采样。true为不需要。
    inter=False #记录采样间隔大小。true为小间隔
    flag=0
    while(cap.isOpened()):
        cap.set(cv2.CAP_PROP_POS_FRAMES, flag)  # 设置帧数标记
        retval, image=cap.read()
        if not retval:
            break

        # if i<=10:
        #     print(flag, inter)
        index+=1
        flag+=int(fps)+inter
        # flag+=1

        inter=not need and 1^inter
        # print('!!!')
        # print(image)
        cv2.imwrite(imgdir+videoname+'_'+str(index)+'.jpg',image)

    # print(flag,i)

        # cap.set(cv2.CAP_PROP_POS_FRAMES, flag)

        # if i==25:
        #     print(cap.get(cv2.CAP_PROP_POS_MSEC)/1000)
            # break
    # print(cap.get(cv2.CAP_PROP_POS_MSEC)/1000)
    # print(i)

import os
import sys
if __name__=="__main__":
    # get_frames("../data/UCF-101_original/ApplyEyeMakeup/v_ApplyEyeMakeup_g01_c01.avi",2,' ')
    '''
    root_o='../data/UCF-101_original' #视频根目录
    root_r='../data/UCF-101'  #输出图片根目录
    if not os.path.exists(root_r):
        os.makedirs(root_r)
    classes=os.listdir(root_o)

    if os.path.exists('./end_c.txt'):
        with open('./end_c.txt') as file:
            cc=file.readline()
            if cc!='':
                cc=cc.strip('\n')
        file.close()
        with open('./end_v.txt') as file:
            ff=file.readline()
            if ff!='':
                ff=ff.strip('\n')
        file.close()
    else:
        cc=''
        ff=''

    try:
        if cc:
            i=classes.index(cc)
            classes=classes[i:]
    
        for c in classes:
            out=root_r+'/'+c+'/'
            video_p=root_o+'/'
            files=os.listdir(video_p+c)
            video=video_p+c+'/'
            print(files[-1])
            if ff:
                i=files.index(ff)
                files=files[i+1:]
                ff=''
            for f in files:
                out_p=out+f.split('.')[0]+'/'
                if not os.path.exists(out_p):
                    os.makedirs(out_p)
                print(video+f, out_p)
                get_frames(video+f, 10, out_p)
    

    except KeyboardInterrupt as e:
        print(str(e))
        with open('./end_c.txt','w') as file:
            file.write(c)
        file.close()
        with open('./end_v.txt','w') as file:
            file.write(f)
        file.close()
#    except Exception as e:
#        print(str(e))
#        with open('./end_c.txt','w') as file:
#            file.write(c)
#        file.close()
#        with open('./end_v.txt','w') as file:
#            file.write(f)
#        file.close()
'''
    get_frames('D:/kaede/data/v_ApplyEyeMakeup_g01_c01.avi', 1, 'D:/kaede/data/test/')


